package jh.com.jhappbf.contract;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.ab.activity.AbActivity;
import com.ab.fragment.AbLoadDialogFragment;
import com.ab.util.AbDialogUtil;
import com.ab.view.titlebar.AbTitleBar;
import com.android.volley.Request.Priority;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import androidx.core.content.ContextCompat;
import jh.com.jhappbf.R;
import jh.com.jhappbf.httputils.VolleyCallWebService;
import jh.com.jhappbf.httputils.VolleySingleton;
import jh.com.jhappbf.model.PlanModel;
import jh.com.jhappbf.ui.State;
import jh.com.jhappbf.utils.ExpressionUtils;
import jh.com.jhappbf.utils.JsonHelper;
import jh.com.jhappbf.weight.query.SelectActivity;

/**
 * @author Administrator
 */
public class PriceAdd extends AbActivity implements OnClickListener {

    private EditText mTxtReceiver;
    private EditText mTxtCargoname;
    private EditText mTxtSender;
    private EditText mTxtType;
    private EditText mTxtPrice;
    private EditText mTxtContractId;
    private EditText mTxtSpec;
    private Context mAppcontext;
    private AbTitleBar mTitleBar;
    private Button mBtnOk;

    private ImageView mReceiverImg;
    private ImageView mCargonameImg;
    private ImageView mSenderImg;
    private ImageView mTypeImg;
    private ImageView mSpecImg;
    private ImageView mContractIdImg;

    private AbLoadDialogFragment mDialogFragment = null;
    private final int GETCARGONAME = 0X0001;
    private final int GETRECEIVER = 0x0002;
    private final int GETTYPE = 0x0003;
    private final int GETSENDER = 0x0004;
    private final int GETSPEC = 0x0005;
    private final int GETCONTRACT = 0x0006;
    private String mAction = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mAppcontext = getApplicationContext();
        setAbContentView(R.layout.price_add_activity);
        Intent intent = getIntent();
        mAction = intent.getStringExtra("action");
        mTitleBar = getTitleBar();
        if ("add".equals(mAction)) {
            mTitleBar.setTitleText("单价添加");
        } else {
            mTitleBar.setTitleText("单价修改");
        }
        mTitleBar.setLogo(R.drawable.button_selector_back);
        mTitleBar.setTitleBarBackgroundColor(ContextCompat.getColor(this, R.color.orange));
        mTitleBar.setTitleTextMargin(10, 0, 0, 0);
        mTitleBar.setLogoLine(R.mipmap.line);
        initView();
    }

    /**
     * 初始化
     */
    private void initView() {
        mTxtReceiver = findViewById(R.id.price_add_receiver_txt);
        mTxtCargoname = findViewById(R.id.price_add_cargoname_txt);
        mTxtPrice = findViewById(R.id.price_add_price_txt);
        mTxtSender = findViewById(R.id.price_add_sender_txt);
        mTxtType = findViewById(R.id.price_add_type_txt);
        mTxtContractId = findViewById(R.id.price_add_contractId_txt);
        mTxtSpec = findViewById(R.id.price_add_spec_txt);

        mReceiverImg = findViewById(R.id.price_add_receiver_img);
        mCargonameImg = findViewById(R.id.price_add_cargoname_img);
        mSenderImg = findViewById(R.id.price_add_sender_img);
        mTypeImg = findViewById(R.id.price_add_type_img);
        mContractIdImg = findViewById(R.id.price_add_ContractId_img);
        mSpecImg = findViewById(R.id.price_add_spec_img);

        mReceiverImg.setOnClickListener(this);
        mCargonameImg.setOnClickListener(this);
        mSenderImg.setOnClickListener(this);
        mTypeImg.setOnClickListener(this);
        mContractIdImg.setOnClickListener(this);
        mSpecImg.setOnClickListener(this);

        View rightView = View.inflate(this, R.layout.title_right_ok_btn_view, null);
        mTitleBar.addRightView(rightView);
        mBtnOk = rightView.findViewById(R.id.title_right_ok_btn);
        mBtnOk.setOnClickListener(v -> {
            String receiver = mTxtReceiver.getText().toString();
            String cargoname = mTxtCargoname.getText().toString();
            String price = mTxtPrice.getText().toString();
            String sender = mTxtSender.getText().toString();
            String type = mTxtType.getText().toString();
            String contractId = mTxtContractId.getText().toString();
            String spec = mTxtSpec.getText().toString();

            if (TextUtils.isEmpty(contractId)) {
                Toast.makeText(PriceAdd.this, "合同单号不能为空!",
                        Toast.LENGTH_SHORT).show();
                return;
            }
            if (TextUtils.isEmpty(receiver)) {
                Toast.makeText(PriceAdd.this, "收货单位不能为空!",
                        Toast.LENGTH_SHORT).show();
                return;
            }
            if (TextUtils.isEmpty(cargoname)) {
                Toast.makeText(PriceAdd.this, "货名不能为空!",
                        Toast.LENGTH_SHORT).show();
                return;
            }
            if (TextUtils.isEmpty(price)) {
                Toast.makeText(PriceAdd.this, "单价不能为空!",
                        Toast.LENGTH_SHORT).show();
                return;
            }

            if (!ExpressionUtils.isNumber(price)) {
                Toast.makeText(PriceAdd.this, "单价不合法!",
                        Toast.LENGTH_SHORT).show();
                return;
            }

            operatorServer(receiver, cargoname, price, sender, type, contractId, spec);
        });

    }

    /**
     * 第一次加载
     */
    private void operatorServer(final String receiver, final String cargoname, final String price, final String sender, final String type, final String ContractId, final String spec) {
        mDialogFragment = AbDialogUtil.showLoadDialog(PriceAdd.this,
                R.mipmap.ic_load, "操作中,请稍等...");
        mDialogFragment.setCancelable(false);
        mDialogFragment.setAbDialogOnLoadListener(() -> addPrice(receiver, cargoname, price, sender, type, ContractId, spec));
    }

    /**
     * 添加计划
     */
    private void addPrice(String receiver, String cargoname, String price, String sender, String type, String contractId, String spec) {
        String methodName = "addPrice";
        ArrayList<String> param = new ArrayList<>();
        ArrayList<String> value = new ArrayList<>();
        param.add("receiver");
        param.add("sender");
        param.add("type");
        param.add("cargoname");
        param.add("price");
        param.add("userName");
        param.add("account");
        param.add("contractId");
        param.add("spec");
        value.add(receiver);
        value.add(sender);
        value.add(type);
        value.add(cargoname);
        value.add(price);
        value.add(State.mName);
        value.add(State.mUserId);
        value.add(contractId);
        value.add(spec);

        Listener<String> listener = response -> {
            AbDialogUtil.removeDialog(PriceAdd.this);
            List<JSONObject> newListData = JsonHelper
                    .getJsonObjects(response);
            if (newListData != null && newListData.size() > 0) {
                JSONObject obj = newListData.get(0);
                String value1 = obj.optString("result");
                String memo = obj.optString("memo");
                if ("true".equals(value1)) {
                    PriceAdd.this.setResult(RESULT_OK);
                    Toast.makeText(PriceAdd.this, memo,
                            Toast.LENGTH_SHORT).show();
                    refresh();
                    //PriceAdd.this.finish();
                } else {
                    Toast.makeText(PriceAdd.this, memo,
                            Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(PriceAdd.this, "操作失败,请重试",
                        Toast.LENGTH_SHORT).show();
            }
        };

        ErrorListener errorListener = error -> {
            AbDialogUtil.removeDialog(PriceAdd.this);
            Toast.makeText(PriceAdd.this, "操作失败,请重试",
                    Toast.LENGTH_SHORT).show();
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(mAppcontext).addRequest(webService);
    }

    /**
     * 刷新
     */
    private void refresh() {
        mTxtCargoname.setText("");
        mTxtContractId.setText("");
        mTxtSender.setText("");
        mTxtReceiver.setText("");
        mTxtPrice.setText("");
        mTxtType.setText("");
        mTxtSpec.setText("");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.price_add_cargoname_img:
                getFieldValue("cargoname1", GETCARGONAME);
                break;
            case R.id.price_add_receiver_img:
                getFieldValue("receiver", GETRECEIVER);
                break;
            case R.id.price_add_sender_img:
                getFieldValue("sender", GETSENDER);
                break;
            case R.id.price_add_type_img:
                getFieldValue("type", GETTYPE);
                break;
            case R.id.price_add_spec_img:
                getFieldValue("spec", GETSPEC);
                break;
            case R.id.price_add_ContractId_img:
                getFieldValue("contract", GETCONTRACT);
                break;
            default:
                break;
        }
    }

    /**
     * 获取字段值
     */
    private void getFieldValue(String field, int value) {
        Intent i = new Intent(PriceAdd.this, SelectActivity.class);
        i.putExtra("flag", field);
        startActivityForResult(i, value);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            Object value;
            if (requestCode == GETCONTRACT) {
                value = data.getParcelableExtra("result");
            } else {
                value = data.getStringExtra("result");
            }
            if (requestCode == GETCARGONAME) {
                mTxtCargoname.setText(String.valueOf(value));
            } else if (requestCode == GETRECEIVER) {
                mTxtReceiver.setText(String.valueOf(value));
            } else if (requestCode == GETSENDER) {
                mTxtSender.setText(String.valueOf(value));
            } else if (requestCode == GETTYPE) {
                mTxtType.setText(String.valueOf(value));
            } else if (requestCode == GETSPEC) {
                mTxtSpec.setText(String.valueOf(value));
            } else if (requestCode == GETCONTRACT) {
                if (value instanceof PlanModel) {
                    PlanModel model = (PlanModel) value;
                    mTxtContractId.setText(model.getPlanId());
                    mTxtReceiver.setText(model.getReceiver());
                    mTxtSender.setText(model.getSender());
                    mTxtType.setText(model.getType());
                }
            }

        }
    }
}